class DB {
  db;
  dataName;
  config;
  version;
  constructor(dataName, config = {}, version = 1) {
    this.dataName = dataName;
    this.config = config;
    this.version = version;
    console.log('new DB');
    this.init();
  }
  init() {
    return new Promise((resolve, reject) => {
      const dataName = this.dataName;
      const version = this.version;
      const config = this.config;

      const req = indexedDB.open(this.dataName, this.version);
      req.onupgradeneeded = (event:any) => {
        console.log('onupgradeneeded');
        const db = event.target.result;
        // 判断是否存在ObjectStore
        if (!db.objectStoreNames.contains(dataName)) {
          // 主键 autoIncrement 自增加
          const store =
            config.keyPath &&
            db.createObjectStore(dataName, { keyPath: config.keyPath, autoIncrement: !!config.autoIncrement });
          // 索引 unique 唯一值
          config.index && store.createIndex(config.index, config.indexKey, { unique: config.indexUnique });
        }
      };
      req.onsuccess = (event:any) => {
        console.log('onsuccess');
        this.db = event.target.result;
        resolve(this.db);
      };
      req.onerror = error => {
        reject(error);
      };
    });
  }
  add(data) {
    return new Promise(async (resolve, reject) => {
      console.log(this.db);
      if (!this.db) {
        await this.init();
      }
      const db = this.db;
      console.log(this.db);
      // 这个时候就报错了
      const transaction = db.transaction([this.dataName], 'readwrite');

      const store = transaction.objectStore(this.dataName);
      const handle = store.add(data);
      handle.onsuccess = () => {
        console.log('新增成功');
        db.close();
        resolve(true);
      };
      handle.onerror = error => {
        console.log('新增失败', error);
        db.close();
        reject(error);
      };
    }).catch(error => console.error(error));
  }
}
